// page/recordCall/index.js
// 录音时麦克风图片集
const record_animate = [
  "/image/record_icon_1.png",
  "/image/record_icon_2.png",
  "/image/record_icon_3.png",
  "/image/record_icon_4.png",
  "/image/record_icon_5.png"
];
// 播放录音时背景图片集
const playVicoeIcons = [
  "/image/playVicoe_1.png",
  "/image/playVicoe_2.png",
  "/image/playVicoe_3.png"
];
const vicoeIconBg = "/image/playVicoe_0.png";
const icon_err = "/image/err_w.png";

let app = getApp();
let config = require('../../config.js');
let selfFlag = "/image/self_se.png";
Page({
  /**
   * 页面的初始数据
   */
  data: {
    islogined:false,
    userInfo:{}, //登陆账号信息
    isRecording:false, //是否录音中
    iscancel:false, //是否取消录音
    recordTime:"60s", //录音时间动画
    startRecordTime:null, //开始录音时间
    record_icon: record_animate[0], //录音时动画图片
    recordMsgArr:[], //录音数据
    systemSetings:{}, //系统设置
    isplay:false, //是否播放
    iscancel:false, //是否取消录音
    clientLnglat:{ x:-1, y:-1 },
    player:-1, //正在播放的id
    playVicoeIcon: vicoeIconBg, //播放录音时动画图片
    playVicoeIconBg: vicoeIconBg
  },
  //计算录音时间
  calcRecordTime:function(){
    if (!this.data.isRecording){ return }
    let that = this;
    let s = parseInt(this.data.recordTime);
    if(s<=0){
      this.recordEnd();
      return;
    }
    s--;
    if (s < 10) {
      s = "0"+s;
    }
    this.setData({
      recordTime: s + "s"
    })
    this.calcRecordTimer=setTimeout(function () {
      that.calcRecordTime();
    }, 1000);
  },
  // 播放录音动画
  playRecordAnimate:function(){
    let that = this;
    //话筒帧动画
    let i=-1;
    function nextPic(){
      i++;
      let k = i % 5;
      that.setData({
        record_icon: record_animate[k]
      })
      that.playRecordTimer=setTimeout(function () {
        if (that.data.isRecording) {
          nextPic();
        }
      }, 200)
    }
    nextPic();
  },
  // 按住录音
  recordStart:function(ev){
    // console.log('touchStart');
    // 判断是否已经登陆
    if (!app.islogined){
      app.jumpTo();
      return
    }
    let that = this;
    // 先获取用户是否已经同意使用录音功能
    wx.getSetting({
      success(res) {
        if (!res['authSetting']['scope.record']) {
          wx.authorize({
            scope: 'scope.record',
            success: function (res) {
              console.log('authorize success', res);
            }
          })
        } else {
          wx.hideToast();
          that.startRecord(ev);
        }
      }
    })
  },
  // 开始录音
  startRecord: function (ev){
    let that=this;
    let startTime = Date.now();
    this.setData({
      isRecording: true,
      startRecordTime: startTime,
      clientLnglat: {
        x: ev.changedTouches[0].clientX,
        y: ev.changedTouches[0].clientY
      }
    })
    that.calcRecordTime();
    that.playRecordAnimate();
    wx.startRecord({
      success: function (res) {
        // 判断是否取消
        if (that.data.iscancel) {
          that.setData({
            iscancel: false
          });
          wx.showToast({
            title: '取消录音',
            icon: "success"
          })
          return;
        }
        // 判断录音时间是否大于1秒
        let endTime = Date.now();
        if (endTime - startTime <= 1000) {
          wx.showToast({
            title: "录音时间太短",
            image: icon_err,
            duration: 2000
          })
          return;
        }
        let tempFilePath = res.tempFilePath;
        //保存文件到本地
        that.saveFileAsLocal(tempFilePath);
      },
      fail: function (res) {
        //录音失败
        console.log("record fail", res);
        wx.showToast({
          title: "录音失败",
          image: icon_err,
          duration: 2000
        })
      }
    })
  },
  // 结束录音
  recordEnd: function () {
    // console.log('touchEnd');
    wx.stopRecord();
    this.setData({
      isRecording: false,
      recordTime:"60s"
    })
    clearTimeout(this.calcRecordTimer);
    clearTimeout(this.playRecordTimer);
  },
  // 取消录音功能
  touchMove: function (ev) {
    let changedTouchesobj = ev.changedTouches[0];
    let clientLnglat = this.data.clientLnglat;
    let move_diff = clientLnglat.y - changedTouchesobj.clientY ;
    if (move_diff>=20){
      this.setData({
        clientLnglat: { x: -1, y: -1 },
        iscancel:true
      })
      this.recordEnd();
      return
    }
  },
  // 播放/停止录音功能
  playOrStopRecord:function(ev){
    let isplay = this.data.isplay;
    if (isplay){
       // 停止播放录音
      this.stopVicoe();
      return;
    }
    let that = this;
    let times = ev.currentTarget.dataset.times;
    let filepath = ev.currentTarget.dataset.filepath;
    let eid = ev.currentTarget.dataset.id;
    // 开始播放录音
    this.playVicoe(filepath, eid, times);
  },
  // 开始播放录音
  playVicoe: function (filepath,eid,times){
    // console.log(filepath, eid, times);
    let that=this;
    // that.playVicoeAnimate(times);
    wx.playVoice({
      filePath: filepath,
      success: function (res) {
        that.setData({
          isplay: true,
          player:eid
        });
        that.playVicoeAnimate(times);
      },
      fail: function (res) {
        console.log("播放异常", res, times);
        that.setData({
          isplay: true,
          playVicoeIcon: vicoeIconBg
        })
        wx.showToast({
          title: "播放异常",
          image: "../../image/err_w.png",
          duration: 3000
        })
      }
    })
  },
  // 停止播放录音
  stopVicoe:function(){
    wx.stopVoice();
    this.setData({
      isplay: false,
      player: -1
    });
    clearTimeout(this.playVicoeTimer);
  },
  //播放录音记录动画
  playVicoeAnimate: function (times){
    let that = this;
    let i = -1;
    // 执行动画
    function play(){
      i++;
      let k = i % 3;
      that.setData({
        playVicoeIcon: playVicoeIcons[k]
      });
      that.playVicoeTimer=setTimeout(function(){
        if (that.data.isplay) {
          play();
        }
      },200);
    }
    play();
    // 录音播放完毕，自动停止
    setTimeout(function(){
      if (that.data.isplay){
        that.stopVicoe();
      }
    }, times);
  },
  // 上传录音文件
  upLoadFile: function (filePath){
    // console.log("uploadFile", filePath);
    wx.uploadFile({
      // url: config.test+'/upload/index.php',
      url: config.uploadUrl+'index.php',
      filePath: filePath,
      name: "file",
      formData:{
        usid:app.userInfo.usid
      },
      header: {
        'content-type': 'multipart/form-data'
      },
      success: function (res) {
        // console.log("uploadFile success", res.data,typeof res.data);
        let rdata=res.data;
        if (typeof rdata === 'string') {
          rdata=JSON.parse(rdata.replace("\ufeff", ""))
        }
        console.log("uploadFile success",rdata);

        // 通过 socket 将消息发送到其他用户上
        let message={
          type:3,
          msg: rdata.fpath
        }
        wx.sendSocketMessage({
          data: [JSON.stringify(message)]
        })

      },
      fail: function (res) {
        console.log("uploadFile fail", res);
      }
    })
  },
  // 保存文件到本地
  saveFileAsLocal: function (tempFilePath){
    let that=this;
    wx.saveFile({
      tempFilePath: tempFilePath,
      success:function(res){
        let savedFilePath = res.savedFilePath;
        let recordMsgArr = that.data.recordMsgArr;
        let startRecordTime = that.data.startRecordTime;
        let timeDiff = (Date.now() - startRecordTime) / 1000;
        let recordLength = that.calc_el_width(timeDiff);
        let showTime = parseInt(timeDiff);
        let msgObj = {
          id: Date.now(),
          stats: 0,
          userFlag: selfFlag,
          nickName: that.data.userInfo.nickName,
          filepath: savedFilePath,
          recordLength: recordLength,
          times: Date.now() - startRecordTime,
          showTime: showTime
        };
        recordMsgArr.push(msgObj);
        that.setData({
          recordMsgArr: recordMsgArr
        })
        console.log('save file', res);
        // 上传文件到服务器
        that.upLoadFile(savedFilePath);
      },
      fail:function(res){
        console.log('save file fail',res);
      },
      complete:function(){
        // console.log('saveFile complete');
      }
    })
  },
  // 获取指定本地文件信息
  getSavedFileInfo: function (filepath){
    wx.getSavedFileInfo({
      filePath: filepath,
      success: function (res) {
        console.log('getSavedFileInfo', res)
      }
    })
  },
  // 获取本地文件列表
  getSavedFileList:function(){
    wx.getSavedFileList({
      success: function (res) {
        console.log("getSavedFileList",res.fileList)
      }
    })
  },
  // 计算界面录音元素宽度
  calc_el_width: function (timeDiff){
    let recordLength;
    if (timeDiff > 20) {
      recordLength = 250;
    } else if (timeDiff > 15) {
      recordLength = 200;
    } else if (timeDiff > 10) {
      recordLength = 150;
    } else if (timeDiff > 5) {
      recordLength = 100;
    } else {
      recordLength = 50;
    }
    return recordLength
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    console.log('onShow');
    if (!app.islogined) {
      app.jumpTo();
      return;
    }
    this.setData({
      userInfo: app.userInfo,
      islogined: app.islogined,
      systemSetings: app.systemSetings
    })
    selfFlag = app.userInfo.flag;
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    console.log('onLoad');
    this.setData({
      recordMsgArr: app.recordMsgArr,
      systemSetings: app.systemSetings
    })
    selfFlag = app.userInfo.flag;

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
  
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
  
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
  
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
  
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
  
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
  
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
  
  }
})
